package com.central.gateway.service;


import com.central.gateway.common.Constants;
import com.central.gateway.common.RiskManageResponseResult;
import com.central.gateway.error.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Map;
import java.util.Objects;

/**
 * 通过http方式调用风控调用
 * @author zouzhihui
 */
@Service
@Slf4j
public class RiskManageHttpService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancer;

    private static final String LB_SCHEME = "lb";

    public RiskManageResponseResult doGet(String url, MultiValueMap<String, String> parameters, HttpHeaders httpHeaders) {
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity(parameters, httpHeaders);
        String uri = getURI(url);
        if (StringUtils.isNotBlank(uri)) {
            ResponseEntity<RiskManageResponseResult> responseResult = restTemplate.getForEntity(uri, RiskManageResponseResult.class, httpEntity);
            return doResponse(responseResult);
        }
        return null;
    }

    public RiskManageResponseResult doPost(String url, String bodyJson, HttpHeaders httpHeaders) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.addAll(httpHeaders);
        HttpEntity<String> httpEntity = new HttpEntity(bodyJson, headers);
        String uri = getURI(url);
        if (StringUtils.isNotBlank(uri)) {
            ResponseEntity<RiskManageResponseResult> responseResult = restTemplate.postForEntity(uri, httpEntity, RiskManageResponseResult.class);
            return doResponse(responseResult);
        }
        return null;
    }

    private RiskManageResponseResult doResponse(ResponseEntity<RiskManageResponseResult> responseResult) {
        if (Objects.nonNull(responseResult.getBody()) && responseResult.getBody().getSuccess()) {
            if (responseResult.getBody().getData() instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) responseResult.getBody().getData();
                if (!(boolean) map.get(Constants.AUDIT_RESULT)) {
                    throw new BusinessException(responseResult.getBody().getErrorCode(), responseResult.getBody().getErrorMessage());
                }
            }
        }
        return responseResult.getBody();
    }

    private String getURI(String url) {
        try {
            URI uri = new URI(url);
            if (LB_SCHEME.equals(uri.getScheme())) {
                ServiceInstance choose = loadBalancer.choose(uri.getHost());
                uri = new URI("http" + url.substring(2));
                uri = loadBalancer.reconstructURI(choose, uri);
            }
            return uri.toString();
        } catch (Exception e) {
            log.error("url参数非法", e);
            //throw new BusinessException("160001", "url参数非法");
        }
        return null;
    }

}
